package com.behome.socket_proxy.netty_D.server;

import com.behome.socket_proxy.netty_D.Constants;
import com.behome.socket_proxy.netty_D.client.NettyClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Map;

public class StandardDNettyServer {

    private static final int PORT = Constants.port; // 服务器端口

    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private ServerBootstrap bootstrap = new ServerBootstrap();
//    private ChannelFuture future;
    private Channel serverChannel;
    public static boolean flag = true;
    private static class SingletonHolder {
        private static final StandardDNettyServer INSTANCE = new StandardDNettyServer();
    }

    // 私有化构造函数，防止外部直接创建实例
    private StandardDNettyServer() {
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new StandardDNettyServerChannelInitializer()); // 自定义初始化器
    }

    // 获取单例对象的方法
    public static StandardDNettyServer getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // 启动服务器
    public void start() throws InterruptedException {
        flag = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        serverChannel = bootstrap.bind(PORT).sync().channel();
    }

    // 关闭服务器
    public void stop() {
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        flag = false;
        for (Map.Entry<Channel, NettyClient> channelNettyClientEntry : StandardDNettyServerHandler.getMap().entrySet()) {
            StandardDNettyServerHandler.removeChannel(channelNettyClientEntry.getKey());
        }
        for (Map.Entry<Channel, NettyClient> channelNettyClientEntry : StandardDNettyServerHandler.getMap2().entrySet()) {
            StandardDNettyServerHandler.removeChannel(channelNettyClientEntry.getKey());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        StandardDNettyServer server = StandardDNettyServer.getInstance();
        server.start(); // 启动服务器

        // 服务器运行一段时间后，可以动态关闭
        // server.stop();
    }
}